<template>
  <div>
    <div class="equip-wrap-common">
      <px-form ref="formRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="日历名称">
              <px-input
                v-model="queryParams.tableName"
                placeholder="请输入日历名称"
                maxlength="50"
                clearable
                @blur="queryParams.planNo = $event.target.value.trim()"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <FactoryArea :factoryArea="factoryAreaCode" @changeFactoryArea="changeFactoryArea" />
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="getDataByNewQuery">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div class="equip-table-btn">
        <px-button v-has="'ERC_EQUIP_CALENDAR_ADD'" style="margin-right: 8px" type="primary" @click="handleAdd">新增值班日历</px-button>
      </div>
      <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 346px)" border>
        <px-table-column label="序号" type="index" width="55" align="center" fixed="left" />
        <template v-for="(item, index) in tableColumns" :key="index">
          <px-table-column
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <template v-if="item.prop === 'tableStatusName'" #default="scope">
              <px-tag v-if="scope.row.tableStatus === 'OFF'" class="ml-[6px]" type="info">{{ scope.row.tableStatusName }}</px-tag>
              <px-tag v-if="scope.row.tableStatus === 'ON'" class="ml-[6px]">{{ scope.row.tableStatusName }}</px-tag>
            </template>
            <template v-else #default="scope">{{
              scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-"
            }}</template>
          </px-table-column>
        </template>
        <px-table-column fixed="right" label="操作" min-width="200" align="center">
          <template #default="scope">
            <px-button link type="primary" @click="handleView(scope.row)">预览</px-button>
            <px-button v-has="'ERC_EQUIP_CALENDAR_EDIT'" link type="primary" @click="handleEdit(scope.row)">编辑</px-button>
            <px-button v-has="'ERC_EQUIP_CALENDAR_OPEN'" link type="primary" :disabled="scope.row.tableStatus === 'ON'" @click="handleOpen(scope.row)"
              >启用</px-button
            >
            <px-button
              v-has="'ERC_EQUIP_CALENDAR_CLOSE'"
              link
              type="primary"
              :disabled="scope.row.tableStatus === 'OFF'"
              @click="handleClose(scope.row)"
              >停用</px-button
            >
            <px-button v-has="'ERC_EQUIP_CALENDAR_DOWNLOAD'" link type="primary" @click="handleDownload(scope.row)">下载</px-button>
            <px-button v-has="'ERC_EQUIP_CALENDAR_DELETE'" link type="primary" @click="handleDelete(scope.row)">删除</px-button>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="getDataByNewQuery"
      />
      <!-- 预览 -->
      <DetailCalender v-model:dialogVisible="detailDialogVisibel" :data="currentData" />
      <!-- 新增/编辑 -->
      <AddCalendar v-model:dialogVisible="addDialogVisibel" :type="calenderType" :data="currentData" @refresh="queryTable" />
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_EQUIP_CALENDAR"
});
import { dutyQuery, dutyUpdate } from "@/api/erc/duty";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from "vue";
import { FactoryArea } from "../inspect/components/index";
import AddCalendar from "./components/AddCalendar.vue";
import DetailCalender from "./components/DetailCalendar.vue";

const detailDialogVisibel = ref(false);
const addDialogVisibel = ref(false);
const formRef = ref();
const state = reactive<any>({
  queryParams: {
    tableName: "",
    pageNum: 1,
    pageSize: 20
  },
  total: 0,
  tableColumns: [
    { prop: "tableName", label: "值班日历名称", minWidth: "200", showOverflowTooltip: true, fixed: "left" },
    { prop: "tableStatusName", label: "值班日历状态", minWidth: "100", showOverflowTooltip: true }
  ],
  tableData: [],
  currentData: null,
  calenderType: ""
});
const { queryParams, tableColumns, total, tableData, currentData, calenderType } = toRefs(state);
const { proxy }: any = getCurrentInstance();
onMounted(() => {
  queryTable();
});
// 地块改变
const changeFactoryArea = (value: any) => {
  queryParams.value.factoryAreaCode = value;
};
// 新增日历项
const handleAdd = () => {
  addDialogVisibel.value = true;
  calenderType.value = "add";
};
// 预览日历项
const handleView = row => {
  currentData.value = row;
  detailDialogVisibel.value = true;
};
// 编辑日历项
const handleEdit = row => {
  currentData.value = { ...row };
  addDialogVisibel.value = true;
  calenderType.value = "edit";
};
// 启用日历项
const handleOpen = row => {
  PxMessageBox.confirm(`确认启用当前值班日历“${row.tableName}”吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await dutyUpdate({
        ...row,
        tableStatus: "ON"
      });
      PxMessage.success("启用成功");
      queryTable();
    })
    .catch(() => {});
};
// 停用日历项
const handleClose = row => {
  PxMessageBox.confirm(`确认停用当前值班日历“${row.tableName}”吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await dutyUpdate({
        ...row,
        tableStatus: "OFF"
      });
      PxMessage.success("停用成功");
      queryTable();
    })
    .catch(() => {});
};
// 下载日历项
const handleDownload = row => {
  const params = {
    id: Number(row.attachment)
  };
  proxy.download("post", "/sharing/api/v1/file/download", params, row.tableName);
};
// 删除日历项
const handleDelete = row => {
  PxMessageBox.confirm(`确认删除当前值班日历“${row.tableName}”吗？删除后不可恢复，请谨慎操作。`, "提示", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await dutyUpdate({
        ...row,
        status: "INVALID"
      });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
// 分页查询任务列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify({ ...queryParams.value, facCode: queryParams.value.factoryAreaCode }));
  const data = await dutyQuery(params);
  tableData.value = data?.data;
  total.value = data?.total;
};
// 改变查询条件并获取人物列表
const getDataByNewQuery = () => {
  queryTable();
};
// 重置筛选条件和巡检清单
const resetTable = async () => {
  queryParams.value = {
    planNo: "",
    taskName: "",
    factoryAreaCode: "",
    taskStatus: "",
    taskType: "",
    pageNum: 1,
    pageSize: 20
  };
  formRef.value.resetFields();
  getDataByNewQuery();
};
watch([detailDialogVisibel, addDialogVisibel], () => {
  if (!detailDialogVisibel.value && !addDialogVisibel.value) {
    currentData.value = null;
  }
});
</script>

<style lang="scss" scoped>
@import url("../scss/table-list.scss");
</style>
